package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.certificate.pojo.MySignUpListVo;
import com.jinzhi.jzweb.domain.ExaminationBatchDO;
import com.jinzhi.jzweb.domain.ExaminationRoomDO;
import com.jinzhi.jzweb.domain.ExceptionAddtimeDO;
import com.jinzhi.jzweb.domain.StuSignUpDO;
import com.jinzhi.jzweb.service.ExaminationBatchService;
import com.jinzhi.jzweb.service.ExaminationRoomService;
import com.jinzhi.jzweb.service.ExceptionAddtimeService;
import com.jinzhi.jzweb.service.StuSignUpService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <pre>
 * 考生异常情况延时记录表
 * </pre>
 * <small> 2020-10-16 08:57:13 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/exceptionAddtime")
public class ExceptionAddtimeController extends BaseController {
    @Autowired
    private ExceptionAddtimeService exceptionAddtimeService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private DictService dictService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private ExaminationRoomService examinationRoomService;

    @GetMapping()
    @RequiresPermissions("jzweb:exceptionAddtime:exceptionAddtime")
    String ExceptionAddtime(Model model) {
        return "jzweb/exceptionAddtime/exceptionAddtime";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:exceptionAddtime:exceptionAddtime")
    public Result<Page<ExceptionAddtimeDO>> list(ExceptionAddtimeDO exceptionAddtimeDTO) {
        // 查询列表数据
        Page<ExceptionAddtimeDO> page = exceptionAddtimeService.selectPage(getPage(ExceptionAddtimeDO.class),
                exceptionAddtimeService.convertToEntityWrapper("stuName", exceptionAddtimeDTO.getStuName()).orderBy("id", false));
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ExceptionAddtimeDO obj = (ExceptionAddtimeDO) page.getRecords().get(i);

            ExaminationBatchDO eBatch = examinationBatchService.selectById(obj.getEbatchId());
            if (eBatch != null) {
                obj.setEbatchName(eBatch.getName());
            }

            StuSignUpDO stu = stuSignUpService.selectById(obj.getStuId());
            if (stu != null) {
                obj.setStuName(stu.getName());
            }

            UserDO userDO = userService.selectById(obj.getCreator());
            if (userDO != null) {
                obj.setCreaterName(userDO.getUsername());
            }

            UserDO user = userService.selectById(obj.getUpdater());
            if (user != null) {
                obj.setUpdateName(user.getUsername());
            }


            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:exceptionAddtime:add")
    String add(Model model) {
        //查询考试批次
        List<ExaminationBatchDO> eBatchList = examinationBatchService.selExamNowList();

        model.addAttribute("ebatch", eBatchList);

        return "jzweb/exceptionAddtime/add";
    }
    
    @GetMapping("/addToRoom")
    @RequiresPermissions("jzweb:exceptionAddtime:addToRoom")
    String addToRoom(Model model) {
    	List<ExaminationBatchDO> eBatchList = examinationBatchService.selExamNowList();
           model.addAttribute("ebatch", eBatchList);
        return "jzweb/exceptionAddtime/addToRoom";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:exceptionAddtime:edit")
    String edit(@PathVariable("id") Long id, Model model) {

        Wrapper<ExaminationBatchDO> wrapper = new EntityWrapper<>();
//		wrapper.eq("state" , 4);
        wrapper.eq("type", 0);

        List<ExaminationBatchDO> eBatchList = examinationBatchService.selectList(wrapper);

        ExceptionAddtimeDO exceptionAddtime = exceptionAddtimeService.selectById(id);

        StuSignUpDO stu = stuSignUpService.selectById(exceptionAddtime.getStuId());
        exceptionAddtime.setStuName(stu.getName());
        exceptionAddtime.setStuNo(stu.getTicketNumber());

        model.addAttribute("ebatch", eBatchList);
        model.addAttribute("exceptionAddtime", exceptionAddtime);
        return "jzweb/exceptionAddtime/edit";
    }

    @Log("添加考生异常情况延时记录表")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:exceptionAddtime:add")
        public Result<String> save(ExceptionAddtimeDO exceptionAddtime) {

        DictDO dic = dictService.findOneByKv("type", "exam_delayed_max_value");

        if (exceptionAddtime.getAddTime() > Integer.parseInt(dic.getValue())) {
            return Result.fail("延时时长不能超过" + dic.getValue() + "分钟！");
        }

        exceptionAddtime.setCreateDate(new Date());
        exceptionAddtime.setCreator(this.getUserId());

        //判断是单个考生还是整过考场
        String  stuNo  = exceptionAddtime.getStuNo();
        MySignUpListVo mySignUpListVo = stuSignUpService.selByUserTickNo(stuNo);
        if(stuNo==null){
            return Result.fail("考生考号错误，请重新输入！");
        }
        
        //考生编号格式：职业技能等级标准代码（3位） +证书等级代码（2位）+年份（2位）+考点序列号（3位）+考场号（2位）+座位号（2位）
        if(mySignUpListVo!=null){
        	Long e = examinationBatchService.findOneByKv("id",exceptionAddtime.getEbatchId()).getId();
                if(!mySignUpListVo.getCbatchId().equals(e)){
                    return Result.fail("考生考号错误,与考生批次不符，请重新输入！");
                }

                exceptionAddtime.setStuId(mySignUpListVo.getId());
                exceptionAddtime.setStuName(mySignUpListVo.getUserName());
                exceptionAddtimeService.insert(exceptionAddtime);
                return Result.ok();
        }else {
            String  stuNo_item ="";
            ArrayList<ExceptionAddtimeDO>  eds = new ArrayList<ExceptionAddtimeDO>();
            for(int i=1;i<100;i++){
                String  no= "";
                if(i<10){
                    no="0"+i;
                }else{
                    no=""+i;
                }
                stuNo_item = stuNo+no;

                MySignUpListVo mySignUpListVoS = stuSignUpService.selByUserTickNo(stuNo_item);

                if(mySignUpListVoS!=null){
                    if(!mySignUpListVoS.getCbatchId().equals( exceptionAddtime.getEbatchId())){
                        continue;
                    }
                    exceptionAddtime.setStuId(mySignUpListVoS.getUserId());
                    exceptionAddtime.setStuNo(stuNo_item);
                    exceptionAddtime.setStuName(mySignUpListVoS.getUserName());

                    ExceptionAddtimeDO tp = new ExceptionAddtimeDO();
                    tp.setEbatchId(exceptionAddtime.getEbatchId());
                    tp.setStuId(exceptionAddtime.getId());
                    tp.setStuName(exceptionAddtime.getStuName());
                    tp.setStuNo(exceptionAddtime.getStuNo());
                    tp.setCreator(exceptionAddtime.getCreator());
                    tp.setCreateDate(exceptionAddtime.getCreateDate());
                    tp.setAddTime(exceptionAddtime.getAddTime());
                    tp.setRemark(exceptionAddtime.getRemark());
                    eds.add(tp);
                }
                //if(stuSignUpService.)
            }
            if(eds.size()<1){
                return Result.fail("考室下未找到考生！");
            }
            try {
                //exceptionAddtimeService.insert(tp);
                exceptionAddtimeService.insertBatch(eds);
            }catch (Exception e){}
        }
        return Result.ok();
    }
    
    @Log("批量添加考生异常情况延时记录表")
    @ResponseBody
    @PostMapping("/saveToRoom")
    @RequiresPermissions("jzweb:exceptionAddtime:addToRoom")
        public Result<String> saveToRoom(Long ebatchId,Long eroomId,int addTime,String remark) {

        DictDO dic = dictService.findOneByKv("type", "exam_delayed_max_value");

        if (addTime > Integer.parseInt(dic.getValue())) {
            return Result.fail("延时时长不能超过" + dic.getValue() + "分钟！");
        }
        UserDO user=getUser();
        
        
        List<StuSignUpDO> stus=stuSignUpService.findByKv("cbatch_id",examinationBatchService.selectById(ebatchId).getCbatchId(),"eallocation_id",eroomId);
        ArrayList<ExceptionAddtimeDO>  eds = new ArrayList<ExceptionAddtimeDO>();
        for(StuSignUpDO s : stus) {
        	//如果非该考点的操作员或超级管理员无法延时
        	if(!s.getOrgId().equals(user.getOrgId())&&userRoleService.listRoleId(getUserId()).indexOf(1l)==-1) {
        		return Result.fail("权限不足！");
        	}
        	ExceptionAddtimeDO tp = new ExceptionAddtimeDO();
        	tp.setEbatchId(ebatchId);
            tp.setStuId(s.getId());
            tp.setStuName(s.getName());
            tp.setStuNo(s.getTicketNumber());
            tp.setCreator(this.getUserId());
            tp.setCreateDate(new Date());
            tp.setAddTime(addTime);
            tp.setRemark(remark);
            eds.add(tp);
        }
        //exceptionAddtime.setCreateDate(new Date());
        //exceptionAddtime.setCreator(this.getUserId());

        //判断是单个考生还是整过考场
        if(eds.size()<1){
            return Result.fail("考室下未找到考生！");
        }
            try {
                //exceptionAddtimeService.insert(tp);
                exceptionAddtimeService.insertBatch(eds);
            }catch (Exception e){}
        
        return Result.ok();
    }

    @Log("修改考生异常情况延时记录表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:exceptionAddtime:edit")
    public Result<String> update(ExceptionAddtimeDO exceptionAddtime) {

        DictDO dic = dictService.findOneByKv("type", "exam_delayed_max_value");
        if (exceptionAddtime.getAddTime() > Integer.parseInt(dic.getValue())) {
            return Result.fail("延时时长不能超过" + dic.getValue() + "分钟！");
        }

        exceptionAddtime.setUpdateDate(new Date());
        exceptionAddtime.setCreator(this.getUserId());

        boolean update = exceptionAddtimeService.updateById(exceptionAddtime);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除考生异常情况延时记录表")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:exceptionAddtime:remove")
    public Result<String> remove(Long id) {
        exceptionAddtimeService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除考生异常情况延时记录表")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:exceptionAddtime:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        exceptionAddtimeService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    @Log("查询考试批次列表-分页")
    @ResponseBody
    @GetMapping("/findStu")
    public Result<?> findStu(String ticketNumber) {
        Wrapper<StuSignUpDO> wrapper = new EntityWrapper<StuSignUpDO>().orderBy("id", false);
        wrapper.eq("org_id", this.getUser().getOrgId());
        if (ticketNumber != null) {
            wrapper.like("ticket_number", ticketNumber);
        }

        Page<StuSignUpDO> page = stuSignUpService.selectPage(getPage(StuSignUpDO.class), wrapper);
//
//		Page<StuSignUpDO> page = stuSignUpService.selectPage(getPage(StuSignUpDO.class),
//				stuSignUpService.convertToEntityWrapper("org_id" ,this.getUser().getOrgId(),"ticket_number",ticketNumber).orderBy("id", false));


        //查询考生
		/*Wrapper<StuSignUpDO> wrapper1 = new EntityWrapper<>();
		wrapper1.eq("org_id" , this.getUser().getOrgId());
		List<StuSignUpDO> stuList = stuSignUpService.selectList(wrapper1);*/

        return Result.ok(page);
    }

    @Log("考生考试延时接口")
    @ResponseBody
    @GetMapping("/delayed")
    public ApiResult<?> delayed(Long stuId, Long eBatchId) {
        ExaminationBatchDO examinationBatchDO = examinationBatchService.selectById(eBatchId);
        ExceptionAddtimeDO ex = exceptionAddtimeService.findOneByKv("ebatchId", eBatchId, "stuId", stuId);
        if (ex != null) {
            Date endDate = new Date();
            endDate.setTime(examinationBatchDO.getEndTime().getTime() + ex.getAddTime() * 60 * 1000);
             Map map = new HashMap();
             map.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endDate));
             return ApiResult.success("请求成功", map);
        }else{
             Map map = new HashMap();
             map.put("endTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(examinationBatchDO.getEndTime().getTime()));
             return ApiResult.success("请求成功", map);
        }

    }


}
